package com.manga.mangaxmlparsing;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.os.Bundle;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;


public class MainActivity extends ListActivity {

	// All static variables
	static final String URL = "https://dl-web.dropbox.com/get/Manga.xml?w=d34aee82";
	// XML Nodes key
	static final String KEY_MANGA = "Manga";
	static final String KEY_TITLE = "Title";
	static final String KEY_CONTENT = "Content";
	static final String KEY_CHAPTERID = "ChapterID";
	static final String KEY_IMAGE = "Image";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ArrayList<HashMap<String, String>> mangaItems = new ArrayList<HashMap<String, String>>();

		XMLParse parse = new XMLParse();
		String xml = parse.getXMLFromUrl(URL);// getting XML
		Document doc = parse.getDomElement(xml);// getting DOM Element
		//
		NodeList nl = doc.getElementsByTagName(KEY_MANGA);
		// looping through all manga nodes <Manga>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			org.w3c.dom.Element e = (org.w3c.dom.Element) nl.item(i);
			// adding each node to HashMap to key => value

			map.put(KEY_TITLE, parse.getValue(e, KEY_TITLE));
			map.put(KEY_CONTENT, parse.getValue(e, KEY_CONTENT));
			map.put(KEY_CHAPTERID, parse.getValue(e, KEY_CHAPTERID));
			map.put(KEY_IMAGE, parse.getValue(e, KEY_IMAGE));

			// adding HashList to ArrayList
			mangaItems.add(map);
		}

		// Adding mangaItems to ListView
		ListAdapter adapter = new SimpleAdapter(this, mangaItems,
				R.layout.list_manga, new String[] { KEY_TITLE, KEY_CONTENT },
				new int[] { R.id.tvMangaTitle, R.id.tvManaContent });
		setListAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
